#include "xdecode_task.h"
#include "xdemux_task.h"
#include "xmux_task.h"
#include "xsdl.h"
#include "xvideo_view.h"
#include <cstring>
#include <windows.h>
#ifdef main
#undef main
#endif // !main
using namespace std;
#define CAM1 "rtsp://127.0.0.1:8554/test"
XDemuxTask *pdet = nullptr;
// 控制台事件处理函数
BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType)
{
  switch (dwCtrlType)
  {
  case CTRL_C_EVENT:
  case CTRL_BREAK_EVENT:
  case CTRL_CLOSE_EVENT:    // 用户点击控制台右上角 ×
  case CTRL_LOGOFF_EVENT:   // 用户注销
  case CTRL_SHUTDOWN_EVENT: // 系统关机
    if (pdet)
    {
      pdet->Stop();
      return TRUE; // 表示已处理
    }
  default:
    return FALSE;
  }
}

int main(int argc, char *argv[])
{
  XDemuxTask demux_task;
  pdet = &demux_task;
  for (;;)
  {
    if (demux_task.Open(CAM1))
    {
      break;
    }
    MSleep(100);
    continue;
  }
  auto vpara = demux_task.CopyVideoPara();
  AVCodecParameters *video_para = nullptr;
  AVCodecParameters *audio_para = nullptr;
  AVRational *video_time_base = nullptr;
  AVRational *audio_time_base = nullptr;
  if (vpara)
  {
    video_para = vpara->para;
    video_time_base = vpara->time_base;
  }
   auto apara = demux_task.CopyAudioPara();
  if (apara)
  {
    audio_para = apara->para;
    audio_time_base = apara->time_base;
  }
XMuxTask mux_task;
  bool ret = mux_task.Open("rtsp_out1.mp4", video_para, video_time_base,
                           audio_para, audio_time_base);
  if (!ret)
  {
    LOGERROR("open mux failed");
    return -1;
  }
  demux_task.set_next(&mux_task);
  demux_task.Start();
  mux_task.Start();
  MSleep(5000);
  mux_task.Stop();
if (!mux_task.Open("rtsp_out2.mp4", video_para, video_time_base,
        audio_para, audio_time_base
    ))
    {
        LOGERROR("mux_task.Open failed!");
        return -1;
    }
    mux_task.Start();
    MSleep(5000);
    mux_task.Stop();
  getchar();
  return 0;
}
